<template>
  <div v-loading="loading">
    <div class="panel">
      <div class="panel-header">
        {{ $route.meta.title }}
      </div>
      <div class="station-cycle-manage__top_radio">
        停用管理：
        <el-radio-group v-model="status">
          <el-radio label="NORMAL">启用</el-radio>
          <el-radio label="STOP">停用</el-radio>
        </el-radio-group>
      </div>
      <div v-if="status === 'STOP'" class="station-cycle-manage__content">
        <el-button
          type="primary"
          class="station-cycle-manage__content__button"
          @click="handleCycleCards"
        >
          {{ cycleCards.length > 0 ? '删除停用周期' : '添加停用周期' }}
        </el-button>
        <span style="color: red">*所选时间段为停用，其余为启用状态</span>
        <CycleSelect
          v-for="(item, index) in cycleCards"
          :key="index"
          ref="select"
          :selectedDays="selectedDays"
          :item="item"
          :showDelete="showDelete"
          @dayschange="
            (val) => {
              handleChangeSelectedDays(val, item)
            }
          "
          @delete="
            (daysOfWeek) => {
              deleteCycleCard(index, daysOfWeek)
            }
          "
        />
        <el-button
          type="success"
          v-if="cycleCards.length > 0"
          @click="addCycleCard"
          >新增停用周期</el-button
        >
      </div>
    </div>
    <div class="panel-btn-wrapper">
      <el-button type="success" @click="handleOk">确认</el-button>
      <el-button type="warning" @click="reset">重置</el-button>
      <el-button type="primary" @click="goBack">返回</el-button>
    </div>
  </div>
</template>
<script>
import CycleSelect from './components/CycleSelect'
import { cycleStopStation, stationDetail } from '@/api/device'
import { cloneDeep } from 'lodash'

const STATUS = {
  NOT_IN_UNABLE_CYCLES: 'NOT_IN_UNABLE_CYCLES', // 无
  IN_UNABLE_CYCLES: 'IN_UNABLE_CYCLES', // 周期停用
  PERMANENT_UNABLE_CYCLES: 'PERMANENT_UNABLE_CYCLES', // 永久停用
  DISABLED_BY_ADMIN: 'DISABLED_BY_ADMIN', // 官方停用
}

export default {
  name: 'StationCycleManagement',
  components: { CycleSelect },
  data() {
    return {
      loading: false,
      resetKey: 0,
      selectedDays: [],
      status: 'NORMAL',
      cycleCards: [],
      defaultCycle: {},
      defaultSelectedDays: [],
    }
  },
  computed: {
    showDelete() {
      return this.cycleCards.length > 1
    },
  },
  mounted() {
    this.getCylcleState()
  },
  methods: {
    goBack() {
      this.$router.push('/device/stationList')
    },
    handleCycleCards() {
      if (this.cycleCards.length > 0) {
        this.selectedDays = []
        this.cycleCards = []
      } else this.addCycleCard()
    },
    getCylcleState() {
      this.loading = true
      stationDetail({
        id: this.$route.params.id,
      })
        .then((res) => {
          if (res.unableCyclesStatus === 'DISABLED_BY_ADMIN') {
            this.$message({
              message: '该电站已被官方停用，请联系管理员解除官方停用',
              showClose: true,
              type: 'warning',
            })

            this.$router.push('/device/stationList')
          }
          if (
            res.unableCyclesStatus == STATUS.IN_UNABLE_CYCLES ||
            res.unableCyclesStatus == STATUS.PERMANENT_UNABLE_CYCLES
          ) {
            this.status = 'STOP'
          } else {
            this.status = 'NORMAL'
          }
          // this.status = res.status
          if (!Array.isArray(res.unableCycles)) {
            this.defaultCycle = []
            this.cycleCards = []
            return
          }

          let tempSelectedArr = []
          this.defaultCycle = cloneDeep(res.unableCycles)
          this.defaultCycle.forEach((item) => {
            tempSelectedArr = tempSelectedArr.concat(item.daysOfWeek)
            if (item.hours.length < 1) return

            try {
              for (let i = 0; i < item.hours.length; i++) {
                let arrStr = item.hours[i].split('-')
                item.hours[i] = [arrStr[0], arrStr[1]]
              }
            } catch (err) {
              console.error(err)
            }
          })

          this.cycleCards = cloneDeep(this.defaultCycle)
          this.defaultSelectedDays = tempSelectedArr
          this.selectedDays = cloneDeep(this.defaultSelectedDays)
        })
        .catch((err) => {
          console.log(err)
        })
        .finally(() => {
          this.loading = false
        })
    },
    deleteCycleCard(index, daysOfWeek) {
      this.cycleCards.splice(index, 1)

      let tempSelectDays = cloneDeep(this.selectedDays)
      daysOfWeek.forEach((item) => {
        let index = tempSelectDays.findIndex((iter) => {
          return iter == item
        })
        if (index >= 0) {
          tempSelectDays.splice(index, 1)
        }
      })

      this.selectedDays = tempSelectDays
    },
    addCycleCard() {
      if (this.cycleCards.length > 6) {
        this.$message({
          message: '最多添加7个停用周期!',
          type: 'warning',
          showClose: true,
        })
        return
      }

      if (this.selectedDays.length > 6) {
        this.$message({
          message: '无时间段可添加',
          type: 'warning',
          showClose: true,
        })

        return
      }
      this.cycleCards.push({
        daysOfWeek: [],
        hours: [],
      })
    },
    handleChange() {},
    handleCycle() {},
    reset() {
      this.cycleCards = cloneDeep(this.defaultCycle)
      this.selectedDays = cloneDeep(this.defaultSelectedDays)
    },
    handleOk() {
      let formValid = true
      if (this.$refs.select) {
        this.$refs.select.forEach((item) => {
          if (!item.validateValue()) {
            formValid = false
            return
          }
        })
      }

      if (!formValid) return

      let unableCycles = cloneDeep(this.cycleCards)

      unableCycles.forEach((item) => {
        if (Array.isArray(item.hours) && item.hours.length > 0) {
          let tempHours = []
          item.hours.forEach((hour) => {
            let fragHoursStr = hour[0] + '-' + hour[1]
            tempHours.push(fragHoursStr)
          })

          item.hours = tempHours
        }
      })

      this.loading = true
      let tmpBol = true
      let unableCyclesStatus = ''

      do {
        if (this.status === 'NORMAL') {
          unableCyclesStatus = STATUS.NOT_IN_UNABLE_CYCLES
          unableCycles = []
          break
        }

        if (unableCycles.length > 0) {
          unableCyclesStatus = STATUS.IN_UNABLE_CYCLES
          break
        }

        unableCyclesStatus = STATUS.PERMANENT_UNABLE_CYCLES
        break
      } while (tmpBol)

      if (unableCyclesStatus == '') return

      cycleStopStation({
        id: this.$route.params.id,
        unableCyclesStatus,
        unableCycles,
      })
        .then(() => {
          this.$message({
            type: 'success',
            message: '保存成功',
            showClose: true,
          })

          this.getCylcleState()

          this.$router.push('/device/stationList')
        })
        .catch((err) => {
          console.log(err)
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleChangeSelectedDays() {
      let arr = []
      this.cycleCards.forEach((item) => {
        arr = arr.concat(item.daysOfWeek)
      })

      this.selectedDays = arr
    },
  },
}
</script>
<style lang="scss" scoped>
.station-cycle-manage__top_radio {
  padding-left: 20px;
}

.station-cycle-manage__content {
  padding: 20px;
}

.station-cycle-manage__content__button {
  height: 40px;
  border-radius: 4px !important;
  margin-bottom: 20px;
}
</style>
